<?php
class MY_Controller extends CI_Controller{
	var $page = "";
	var $mainmodel = "";
	var $folder = "site";
	var $action = '';
	var $submitted = FALSE;
	var $currentUrl = BASE_URL;
	var $custom = false;
	var $nextaction = "";
	var $validationResult  = FALSE;
	var $validationMessage  = array();
	var $PERMISSION = array();
	var $isJSON = FALSE;
	var $isAjaxRequest = FALSE;
	var $redirected = FALSE;
	VAR $rediredtURL = "";
	var $hasFile = FALSE;
	var $skipParentConstructor = FALSE;
	var $displayDataOnly = FALSE;
	
	
	function __construct(){
		parent::__construct();
		if(!$this->skipParentConstructor){
			$this->benchmark->mark('start');
			$this->action = $this->router->fetch_method();
			$this->initialize();
		}
	}
	

	
	function initialize(){
		if($this->action == "index" || $this->action == "notfound" || $this->action == "search" )
			$this->action = "";
			
		if($this->action == "byitem" || $this->action == "by_field" ||  $this->action == "byfield_a" || $this->action == "listall_a")
			$this->action = "ajax";
			
		if($this->input->post("submit",TRUE)!="")
			$this->submitted = TRUE;
			
		if($this->page == "")
			$this->page = strtolower(get_called_class());
			
		$this->loadpermissions();
	}
	
	function loadpermissions(){
		$this->PERMISSION = $this->mDevPagePermission->loadpermission($this->page);
	
	}
	
	function index(){
		$data = array();
		if($this->folder == ADMIN || $this->folder == DEVELOPER ){
			$data['searchCriteria'] = $this->mainmodel->searchfields;
			$data['fields'] = $this->mainmodel->mainlistfields;
			$data['record'] = $this->mainmodel->mainListWithPagination();
			
		}
		$this->maindata($data);
	}
	public function add(){
		if($this->PERMISSION[CAN_ADD]){
			$data = array();
			$this->nextaction = "insert";
			$data['fields'] = $this->mainmodel->editablefields;
			$data[DROPDOWN] = $this->setDropdownValues();
			$data[CKEDITOR] = $this->configureCKEditor("add");
			$this->maindata($data);
		}
	}
	
	public function edit($id = ""){
		$data = array();
		
		if($id != "" && $this->PERMISSION[CAN_EDIT]){  
			$this->nextaction = "update";
			$data["record"] = $this->mainmodel->find_editable($id);
			$data['fields'] = $this->mainmodel->editablefields;
			$data['ID'] = $id;
			$data[DROPDOWN] = $this->setDropdownValues();
			$data[CKEDITOR] = $this->configureCKEditor($id);
			$this->maindata($data);
		}else 
			$this->redirecttorecordlist();
		
	}
	
	function edit2($id = ""){
		$this->edit($id);
	}
	
	public function ajaxdelete($id = ""){
		if($id != "" && $this->PERMISSION[CAN_DELETE]){
			$this->mainmodel->delete($id);
			$linkspon["success"]= "success";
			$this->loadjson($linkspon);
			return;
		}
			
	}
	
	public function delete($id = ""){
		$data = array();
		$this->action = "";
		if($id != "" && $this->PERMISSION[CAN_DELETE])
			$this->mainmodel->delete($id);
		$this->redirecttorecordlist();
	}
	public function view($id = ""){
		$data = array();
		if($id != "" && $this->PERMISSION[CAN_VIEW]){
			//echo "CAN VIEW--------------".$this->PERMISSION[CAN_VIEW]."   action " . $this->action;
			$this->nextaction = "view";
			$data["record"] = $this->mainmodel->find($id);
			$data['fields'] = $this->mainmodel->viewablefields;
			$data[DROPDOWN] = $this->setDropdownValues();
			$data[CKEDITOR] = $this->configureCKEditor($id);
			$this->maindata($data);
		}else
			 $this->redirecttorecordlist();
		
		
	}
	public function insert(){
		$data = array();
		if($this->submitted && $this->PERMISSION[CAN_ADD]){
			$POSTED_VALUES = $this->setValues();
			
			$this->validationResult =  $this->form_validation->run();
			$this->nextaction = "insert";
			$data['fields'] = $this->mainmodel->editablefields;
			$data[DROPDOWN] = $this->setDropdownValues();
			$data[CKEDITOR] = $this->configureCKEditor($id);
			if($this->validationResult == TRUE){
				if($this->hasFile){
					$this->uploadImage();
				}
				$this->mainmodel->insert($POSTED_VALUES);
				
				$this->edit($this->mainmodel->last_inserted_id());
				
			}else
				$this->maindata($data);
		} else
			$this->redirecttorecordlist();
		
	}
	
	public function ajaxinsert(){
		$isAjaxRequest = TRUE;
		$data = array();
		$linkspon["success"] = "failed";
		$linkspon["validationmessage"] = "";
		if($this->PERMISSION[CAN_ADD]){
			$POSTED_VALUES = $this->setValues();
			$this->action = "ajax";
			$this->validationResult =  $this->form_validation->run();
			$linkspon["validationmessage"] = "";
			if($this->validationResult){
				$this->mainmodel->insert($POSTED_VALUES);
				$linkspon["success"]= "success";
				$linkspon["id"]= $this->mainmodel->max_id();
				$this->loadjson($linkspon);
				return;
			}else{
				$linkspon["validationmessage"] = validation_errors();
				$this->loadjson($linkspon);
			}
		}else
			$this->loadjson($linkspon);
		
	}
	
	public function update($id = ""){
		$data = array();
		if($id != "" && $this->submitted && $this->PERMISSION[CAN_EDIT]){
			$POSTED_VALUES = $this->setValues($id);
			$this->validationResult =  $this->form_validation->run();
			$this->nextaction = "update";
			$data['ID'] = $id;
			$data['fields'] = $this->mainmodel->editablefields;
			$data[DROPDOWN] = $this->setDropdownValues();
			$data[CKEDITOR] = $this->configureCKEditor($id);
			if($this->validationResult){
				$POSTED_VALUES['id'] = $id;
				$this->mainmodel->update($POSTED_VALUES);
				$this->postUpdate($id);
			}
			$this->maindata($data);
		}else 
			$this->redirecttorecordlist();
		
	}
	
	function ajaxupdate($id = ""){
			$data = array();
		//	echo "HEREEEEEEEEEEE";
			$linkspon["success"]= "failed";
			//echo("11111111111111 (".($id != "" && $this->PERMISSION[CAN_EDIT]).")");
			if($id != "" && $this->PERMISSION[CAN_EDIT]){
				//echo "HERE 1";
				$POSTED_VALUES = $this->setValues($id);
				//echo "HERE 2";
				$this->action = "ajax";
				$this->validationResult =  $this->form_validation->run();
				//echo "HERE 3";
				$linkspon["success"] = "failed";
			
				$this->nextaction = "update";
				$data['ID'] = $id;
				$data['fields'] = $this->mainmodel->editablefields;
				//$data[DROPDOWN] = $this->setDropdownValues();
				//echo "----".validation_errors()."";
				if($this->validationResult){
					$linkspon["success"] = "success";
					$POSTED_VALUES['id'] = $id;
					$this->mainmodel->update($POSTED_VALUES);
					$linkspon["id"]= $id;
					$this->postUpdate($id);
					$this->loadjson($linkspon);
				}else{
					$linkspon["validationmessage"] = validation_errors();
					$this->loadjson($linkspon);
				}
					
			}else 
				$this->loadjson($linkspon);
	}
	
	public function search(){
		if( $this->submitted && $this->PERMISSION[CAN_SEARCH]){
		    $data = array();
			$this->setSearchValues();
			$this->index();
		}else 
			$this->redirecttorecordlist();
	}
	
	function maindata($data = array()){
		$data['ALLOWEDPAGES'] = $this->mDevPagePermission->loadallowedpages();
		$data['PERMISSION'] = $this->PERMISSION;
		$data['NAVIGATION'] = $this->mDevNavigation->loadNavigation();
		$data['DESTINATION'] = $this->PERMISSION['folder'];
		$data['URL'] = base_url()."/".$this->PERMISSION['folder'];
		$this->loadPage($data);
	}
	
	function loadPage($data = array()){
		$data['action'] = $this->action;
		//for sites
		$data['page'] = $this->page;
		$data['nextaction'] = $this->nextaction;
		$data['validationResult'] = $this->validationResult;
		$data['CAPTION'] = humanize($this->page);
		if($this->redirected && $this->rediredtURL != ""){
			//this page is a child of another page,
		}else{
			if($data['PERMISSION']['custom']){
				$data['CUSTOMREFERENCE'] = $this->loadCustomReferenceData($data);
				$this->parser->parse('/admin/custompages', $data);
			}else{
				$this->parser->parse('/default', $data);
			}
			$this->benchmark->mark('end');
		}
	}
	

	function loadCustomReferenceData($data = array()){
		echo "called";
	}
	
	function setValues($id = ""){
		
		$this->load->library('form_validation');
		$POSTED_VALUES = array();
		forEach($this->mainmodel->editablefields[DATA] as $field){
			$otherValidation = "";
			$required = $field[REQUIRED];
			$unique = $field[UNIQUE];
			
			$isFile= ($field[TYPE] == "file") ? TRUE : FALSE;
			$field = $field[FIELDS];
			
			
			if($unique)
				if($this->action == "insert"){
					$otherValidation = "|is_unique[".$this->mainmodel->table().".".$field."]";
				}else if($this->action == "update"){
					$otherValidation = "|callback_check_duplicate[$id-$field]";
				}
			
			//echo "$field NULL : " .(isset($_FILES[trim($field)]));
			//echo "$field ----->>> IS FILE: $isFile <br>";
			//;
			if($isFile){
				//$this->uploadImage();
				
				$this->form_validation->set_rules($field, humanize($field), "trim|xss_clean".(($required)?"|required":"").$otherValidation);
				//$POSTED_VALUES[trim($field)] = $_FILES[trim($field)];
				echo "(((".$_FILES[$field]['name'].")))))";
					if (empty($_FILES[$field]['name']))
					{
					  $this->form_validation->set_rules($field, humanize($field), "trim|xss_clean".(($required)?"|required":"").$otherValidation);
					}else{
						$this->hasFile = TRUE;
					}
			}else{
				$this->form_validation->set_value($field);
				$this->form_validation->set_rules($field, humanize($field), "trim|xss_clean".(($required)?"|required":"").$otherValidation);
				$POSTED_VALUES[trim($field)] = $this->input->post($field, TRUE);
			}
			$this->otherValidationRules();
		}
		return $POSTED_VALUES;
	}
	
	function check_duplicate($value , $field){
		$details = explode("-" , $field);
		if($this->mainmodel->check_duplicate($details[0] , $details[1] , $value)){
			$this->form_validation->set_message("check_duplicate","The ".humanize($details[1])."  must be unique.");
			return false;
		}else
			return true;
	}
	
	function otherValidationRules(){}
	
	function setDropdownValues(){
		return $this->mainmodel->getDataForDropdown();
	}
	
	function setSearchValues(){
		forEach($this->mainmodel->searchfields[DATA] as $fields){
			$this->form_validation->set_value($fields[FIELDS]);
			$this->form_validation->set_rules($fields[FIELDS], humanize($fields[FIELDS]), "trim|xss_clean");
			
			$this->db->select($fields[FIELDS]);
		}
	}
	
	function postUpdate($id){
		//echo "POST UPDATE $id<br>";
	}
	
	
	function redirecttorecordlist(){
		REDIRECT(BASE_URL."/".$this->folder."/".$this->page);
	}
	
    function redirecttologin(){
		$this->redirecttorecordlist();
	}
	
	function postConstructor(){
		$this->hasCurrentUser();
	}
	
	
	function  hasCurrentUser(){
		//echo "HAS CURRENT USER  .....".$this->folder."---".$this->page."((((((".$this->session->userdata(ADMIN_USER_ID).")))))" ;
		if($this->folder == ADMIN || $this->folder == DEVELOPER){
			if($this->page != "login"){
				if($this->session->userdata(ADMIN_USER_ID) == "" || $this->session->userdata(ADMIN_USER_ID) == null){
					//echo "......LOGINPAGE..........";
					$this->page = "login";
					$this->redirecttorecordlist();
				}
			}
		}
	}
	
	
	function loadoptions($field , $value){
		$array = $this->mainmodel->loadoptionsbyfield($field , $value);
		//ECHO "count.... ".count($array);
		$this->loadjson($array);
	}
	
	function byfield_a($field = "", $value = ""){
		//echo  "($field)))(($value)))";
		//$field = $field;
		$this->isAjaxRequest = TRUE;
		$this->byfield($field."", $value);
	}
	
	function byfield_data_only($field = "", $value = ""){
		$this->action="data-list-only";
		$this->byfield($field, $value);
	}
	
	function byfield($field, $value){
		
			$data = array();
			//echo $this->isAjaxRequest."-------------".$this->page."(".$this->isAjaxRequest.")".$this->action;
			if($this->isAjaxRequest){
			//	echo "HHHHH";
			//	$this->mainmodel->mainlistfields  = $this->mainmodel->ajaxmainlistfields;
			}
				
			$data['fields'] = $this->mainmodel->mainlistfields;
			//echo "FIELDDDD   ". $field . "     $value";
			$data['record'] = $this->mainmodel->mainListWithPaginationByField($field  , $value);
			
			
			$data['query_field'] = $field;
			$data['query_value'] = $value;
		    $this->maindata($data);
	}
	
	function listall_a(){
		$data = array();
			if($this->isAjaxRequest)
				$this->mainmodel->mainlistfields  = $this->mainmodel->ajaxmainlistfields;
			
			$data['fields'] = $this->mainmodel->mainlistfields;
			$data['record'] = $this->mainmodel->mainListWithPagination();
		    $this->maindata($data);
		
	}
	
	
	//START OF CODE FOR PER COMPANY
	function byitem($itemid = ""){
		$data = array();
			$data['searchCriteria'] = $this->mainmodel->searchfields;
			$data['fields'] = $this->mainmodel->mainlistfields;
			$data['record'] = $this->mainmodel->mainListWithPaginationByField("item_id" , $itemid);
			
		$this->maindata($data);
	}
	
	function gggggg(){
		$linkspon["success"]= "success";
		$this->loadjson($linkspon);
	}
	
	function loadjson($array = array()){
		header('Content-type: application/json');
   	    echo json_encode($array);
	}
	
	private function uploadImage() {
		echo "UPLOADDDSSSSSSSSSS" . file_exists('./uploads/');
		$config['upload_path'] = './uploadeds';
		$config['allowed_types'] = 'gif|jpg|png|txt|xls|xlsx';

		$this->load->library('upload', $config);
		

		if ( ! $this->upload->do_upload())
		{
			$error = array('error' => $this->upload->display_errors());

			echo "ERRROOOOOORR:  ". $this->upload->display_errors();
		}
		else
		{
			$data = array('upload_data' => $this->upload->data());

			ECHO "SUUUUCCCCESSSSSS";
			//$this->load->view('upload_success', $data);
		}
	
	}
	
	
	private function createDirectory() {
		if(!is_dir(IMAGE_PATH))
	    	mkdir(IMAGE_PATH,DIR_WRITE_MODE,TRUE);
    	
	   	if(!is_dir(ORIGINAL_IMAGE_PATH))
	    	mkdir(ORIGINAL_IMAGE_PATH,DIR_WRITE_MODE,TRUE);
	    	
		if(!is_dir(THUMBNAIL_IMAGE_PATH))
			mkdir(THUMBNAIL_IMAGE_PATH,DIR_WRITE_MODE,TRUE);
		
	}
	
	function configureCKEditor($identifier = ""){
		//this is the default
		$this->load->helper('ckeditor');
		
		$CKEDITOR = array();
		
		$ckeditorfields = $this->mainmodel->getCKEditorFields();
		//echo "COUNT::::::::------(" . count($ckeditorfields[DATA]) . "))";
		if(count($ckeditorfields[DATA]) > 0)
			forEach($ckeditorfields[DATA] as $ckeditor)
				$CKEDITOR[$ckeditor[FIELDS]] = array(
					//ID of the textarea that will be replaced
					'id' 	=> 	"ckeditor_".$identifier."_".$ckeditor[FIELDS],
					'path'	=>	'../coreassets/core/assets/ckeditor',
		 
					//Optionnal values
					'config' => array(
						'width' 	=> 	"550px",	//Setting a custom width
						'height' 	=> 	'100px',	//Setting a custom height
						'toolbar' 	=> 	array(	//Setting a custom toolbar
							array('Bold', 'Italic'),
							array('Underline', 'Strike', 'FontSize'),
							array('Smiley'),
							'/'
						)
					),
		 
					//Replacing styles from the "Styles tool"
					'styles' => array(
						//Creating a new style named "style 1"
						'style 3' => array (
							'name' 		=> 	'Green Title',
							'element' 	=> 	'h3',
							'styles' => array(
								'color' 	=> 	'Green',
								'font-weight' 	=> 	'bold'
							)
						)
		 
					)
				);
			//var_dump($ckeditorfields[DATA]);
			
			return $CKEDITOR;
	}
	
	function loadimage(){
		//header("Content-Type: image/jpg");
		echo "YOHANTENMA";
	}
}
?>